<style scoped>
#page-login {
    height: 100vh;
    display: flex;
    background-color: pink;
}

.login-wrapper {
    width: 800px;
    margin: auto;
    background-color: #fff;
    padding: 30px;
    border-radius: 5px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
}

.left-picture {
    display: flex;
    align-items: center;
    border-right: dashed 1px #ccc;
}

.logo-icon {
    width: 300px;
    height: 300px;
    margin: auto;
    fill: #999999;
}

.login-form {
    width: 350px;
    padding: 50px;
}

.title {
    text-align: center;
    margin-bottom: 40px;
}

.input-item {
    margin-bottom: 30px;
}

.forget-tips {
    text-align: center;
}

.reset-link {
    text-decoration: none;
    color: #999999;
}

.input-code-item {
    position: relative;
}

.verify-code {
    height: 35px;
    position: absolute;
    right: 2px;
    top: 2px;
}
</style>
<template>
    <div id="page-login">
        <div class="login-wrapper d-flex">
            <div class="flex-1 left-picture">
                <app-logo class="logo-icon" />
            </div>
            <div class="login-form">
                <h1 class="title">天牛网盘</h1>
                <el-form
                    ref="form"
                    :model="loginForm"
                    :rules="rules"
                    status-icon
                    size="large"
                    @keyup.enter="submitForm"
                >
                    <el-form-item label="" prop="username" class="input-item">
                        <el-input v-model="loginForm.username" placeholder="用户名" autocomplete="off"/>
                    </el-form-item>
                    <el-form-item label="" prop="password" class="input-item">
                        <el-input v-model="loginForm.password" placeholder="登录密码" type="password" autocomplete="off"/>
                    </el-form-item>
                    <el-form-item label="" prop="code" class="input-item input-code-item">
                        <el-input v-model="loginForm.code" placeholder="验证码" autocomplete="off"/>
                        <img @click="refreshCode" :src="currentCodeSrc" class="verify-code" alt="">
                    </el-form-item>
                    <el-form-item>
                        <el-button :loading="loginLoading" style="width: 100%" type="primary" @click="submitForm">登录
                        </el-button>
                    </el-form-item>
                    <div class="forget-tips" style="overflow:hidden;">
                        <div style="float: left">
                            <router-link class="reset-link" to="/forget">密码忘记了,点我重置密码！</router-link>
                        </div>
                        <div style="float: right">
                            <router-link class="reset-link" to="/reg">注册账号</router-link>
                        </div>
                    </div>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
import {defineComponent, onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from 'vue-router'
import {useStore} from "vuex";
import api from "../service/api";
import AppLogo from "../components/AppLogo.vue";

export default defineComponent({
    name: 'Login',
    components: {AppLogo},
    method: {
        gotoMain() {
            this.$router.push('/');
        }
    },
    setup() {
        /**
         *
         * @type {Ref<FormInstance>}
         */
        const form = ref(null);
        // 生成验证码所需要的标识
        const codeId = crypto.randomUUID();
        // 使用reactive将对象转换成响应对象
        const loginForm = reactive({
            password: '',
            username: '',
            code: '',
            codeId
        })
        // 验证码的图片路径
        const currentCodeSrc = ref('')
        // 刷新验证码
        const refreshCode = ()=>{
            // 客户端自己生成的标识 创建验证码
            //currentCodeSrc.value = '//localhost:8080/code?id=' + loginForm.codeId + '&r=' + Math.random();
            api.code().then(ret=>{
                // console.log(ret)
                loginForm.codeId = ret.id
                currentCodeSrc.value = ret.image
            });
        }

        // 已加载 刷新验证码
        onMounted(()=>{
            refreshCode()
        })

        const checkPassword = (rule, value, callback) => {
            if (!value) callback(Error('请填写密码')) // 验证不通过
            else callback() // 验证通过
        }
        const rules = reactive({
            username: [
                {required: true, message: '请填写用户名称', trigger: 'blur'}
            ],
            password: [
                {validator: checkPassword, trigger: 'blur'}
            ]
        })
        const router = useRouter(); // 获取路由对象
        const store = useStore();
        const loginLoading = ref(false)
        const submitForm = () => {
            if (loginLoading.value) return;
            // 验证表单
            form.value.validate(async (isValid) => {
                if (isValid) {
                    // 设置loading未true
                    loginLoading.value = true
                    try {
                        // 调用action中对应的一些方法
                        // 由于整体采用同步代码 所以action的方法必须返回Promise对象
                        const _data = await store.dispatch('login', loginForm)
                        // 登录成功后 需要保存token
                        // localStorage.setItem('token',_data);
                        ElMessage.success('登录成功')
                        router.replace('/').then().catch();
                    } catch (e) {
                        refreshCode()
                        ElMessage.error(e.message || '登录错误')
                    } finally {
                        loginLoading.value = false
                    }
                }
            })
        };
        return {
            loginForm, submitForm, rules, form, loginLoading,refreshCode,currentCodeSrc
        }
    }
})
</script>
